<template>
  <Dialog v-model="dialogVisible" :title="dialogState.dialogTitle" :width="dialogState.dialogWidth">
    <el-form
      :model="form"
      label-width="96px"
      ref="Step1Ref"
      :rules="formStep1Rules"
      v-show="step === 1"
    >
      <el-form-item label="任务名称" prop="name">
        <ns-input v-model="form.name" clearable placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="测试策略" prop="strategyName">
        <ns-input
          v-model="form.strategyName"
          clearable
          placeholder="请选择测试策略"
          readonly
          @click="showStrategy"
        />
      </el-form-item>
    </el-form>
    <div v-show="step === 2">
      <SelectFile ref="file" @success="getFile" />
    </div>

    <template #footer>
      <!-- <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button> -->

      <el-button type="primary" @click="handleSubmit">{{
        step === 1 ? '下 一 步' : '生成并保存测试方案'
      }}</el-button>
      <el-button v-if="step === 2" type="primary" @click="preStep">重置测试方案</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <SelectStrategy
    v-model:visible="strategyVisible"
    :type="form.id ? 'update' : 'create'"
    v-if="strategyVisible"
    @success="getStrategy"
  />
</template>
<script setup>
import SelectFile from './file.vue'
import SelectStrategy from './strategy.vue'
import {
  createStrategyTestingBatch,
  updateStrategyTesting,
  getStrategyTesting
} from '@/api/develop/strategyTesting'
import { cloneDeep } from 'lodash-es'
const message = useMessage() // 消息弹窗
const dialogVisible = defineModel('visible', { type: Boolean })
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  dialogTitle: {
    type: String,
    default: ''
  }
})
const dialogState = computed(() => {
  const state = {
    dialogWidth: 400,
    dialogTitle: props.dialogTitle
  }
  if (step.value === 2) {
    state.dialogTitle = '选择文件'
    state.dialogWidth = 1000
  }
  return state
})
const step = ref(1)
const form = ref({
  name: '',
  strategyName: '',
  manageIdName: ''
})
const formStep1Rules = reactive({
  name: [{ required: true, message: '任务名称不能为空', trigger: ['blur', 'change'] }],
  strategyName: [{ required: true, message: '测试方案不能为空', trigger: ['blur', 'change'] }]
})
const emits = defineEmits(['update:visible', 'success'])

watch(
  () => dialogVisible.value,
  (val) => {
    if (val) {
      step.value = 1
    }
  }
)
/** 上一步 */
function preStep() {
  step.value = 1

  form.value.name = null
  form.value.strategyName = null
  manageIds = null
  reverseManageIds = null
  strategyId = null
  // Step1Ref.value?.resetFields()
}

const Step1Ref = ref()
// const getDetail = async () => {
//   if (!props.id) return
//   form.value = await getStrategyTesting({ id: props.id })
//   manageIds = form.value.manageIds
//   strategyId = form.value.strategyId
// }
const handleSubmit = async (e) => {
  console.log('form.value', form.value)
  e.preventDefault()
  // 校验表单
  if (step.value === 1) {
    await Step1Ref.value?.validate()
    showFile()
    // 下一步
    step.value = 2
    file.value.setTable(manageIds?.split(','), reverseManageIds?.split(','))
    return
  }
  await file.value.submitForm()
  const params = strategyId.map((item, index) => {
    return {
      name: form.value.id ? form.value.name : form.value.name + '-' + String(index + 1),
      strategyId: item.id,
      manageIds,
      reverseManageIds
    }
  })
  console.log('params', params)
  // return

  if (form.value.id) {
    params.id = form.value.id
  }
  const api = params.id ? updateStrategyTesting : createStrategyTestingBatch
  await api(params)
  message.success('操作成功')
  emits('success')
  dialogVisible.value = false
}

const file = ref()
const showFile = () => {
  file.value.open()
}

const strategyVisible = ref()
const showStrategy = () => {
  strategyVisible.value = true
}

let manageIds = ''
let reverseManageIds = []
const getFile = (val, rightFiles) => {
  let fileNameList = []
  let fileIdList = []
  val.forEach((item) => {
    fileNameList.push(item.name)
    fileIdList.push(item.id)
  })
  form.value.manageIdName = fileNameList.join(',')
  manageIds = fileIdList.join(',')
  reverseManageIds = rightFiles.map((item) => item.id).join(',')
}

// 测试方案id
let strategyId = ''
const getStrategy = (val) => {
  form.value.strategyName = val.map((item) => item.strategyName).join(',')
  strategyId = val
}

const setFormData = (val = {}) => {
  form.value = cloneDeep(val)
  manageIds = form.value.manageIds
  reverseManageIds = form.value.reverseManageIds
  strategyId = form.value.strategyId?.split(',').map((item) => item.id)
}
defineExpose({
  setFormData
})
</script>
